import {
  ConstructionScheme,
  CrossingPoint,
  Project,
  User,
} from "@/api/entities";

// This file is now the single source of truth for MD template rendering.

/**
 * 模板引擎所需的数据准备逻辑
 */
export const prepareTemplateData = (
  scheme,
  crossingPoint,
  project,
  user = null
) => {
  const data = {};

  // Helper functions for labels
  const getCrossingTypeLabel = (type) => {
    const typeMap = {};
    return typeMap[type || ""] || type || "N/A";
  };

  const getDifficultyLabel = (level) => {
    const labelMap = {
      low: "低难度",
      medium: "中等难度",
      high: "高难度",
      critical: "极高难度",
    };
    return labelMap[level || ""] || level || "N/A";
  };
  const camelToSnake = (str) => {
    return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
  };
  const getApprovalStatusLabel = (status) => {
    const statusMap = {
      draft: "草稿",
      review: "审核中",
      approved: "已批准",
      rejected: "已拒绝",
    };
    return statusMap[status || ""] || status || "N/A";
  };

  // New helper function for cost estimation
  const estimateCost = (baseCost, difficulty) => {
    let multiplier = 1.0;
    if (difficulty === "medium") multiplier = 1.2;
    else if (difficulty === "high") multiplier = 1.5;
    else if (difficulty === "critical") multiplier = 2.0;
    return baseCost * multiplier;
  };

  // Determine difficulty level from crossing point
  const difficulty = crossingPoint?.difficultyLevel;

  // Recommendations array, with duration in days
  const recommendations = [
    {
      method: "helicopterStringing",
      name: "直升机架线法",
      score: 95,
      cost: estimateCost(15, difficulty),
      duration: 2, // Duration in days
      personnel: 8,
      risk:
        difficulty === "high" || difficulty === "critical" ? "medium" : "low",
      reasoning:
        "采用直升机进行架线作业，可快速完成跨越，减少对交通的影响，适合高难度跨越场景。",
      pros: [
        "施工速度快，工期短",
        "对交通影响最小",
        "技术成熟，安全可靠",
        "不需要大面积场地准备",
      ],
      cons: ["成本相对较高", "受天气影响较大", "需要专业直升机作业队伍"],
      equipment: ["直升机", "牵引设备", "通信设备", "安全防护用具"],
      environmental: "对环境影响最小，无需大规模场地清理",
    },
    {
      method: "groundStringing",
      name: "地面拖拉架线法",
      score: 80,
      cost: estimateCost(8, difficulty),
      duration: 3, // Duration in days
      personnel: 12,
      risk: difficulty === "critical" ? "high" : "medium",
      reasoning: "采用地面拖拉设备进行架线，成本适中，适用于多数跨越场景。",
      pros: ["成本相对较低", "设备投入适中", "技术要求不高", "作业相对灵活"],
      cons: ["需要较长封路时间", "对交通影响较大", "受地形条件限制"],
      equipment: ["拖拉机械", "滑轮组", "钢丝绳", "张力放线设备"],
      environmental: "需要临时道路和作业场地，对环境有一定影响",
    },
    {
      method: "manualStringing",
      name: "人工牵引架线法",
      score: 60,
      cost: estimateCost(5, difficulty),
      duration: 5, // Duration in days
      personnel: 20,
      risk:
        difficulty === "critical"
          ? "high"
          : difficulty === "high"
          ? "medium"
          : "low",
      reasoning:
        "采用人工方式进行架线，成本最低，但工期较长，适合简单跨越场景。",
      pros: ["成本最低", "设备需求最少", "对环境扰动小", "作业灵活性高"],
      cons: ["工期较长", "劳动强度大", "受人员技能影响", "不适合复杂跨越"],
      equipment: ["手摇绞车", "滑轮", "安全绳索", "基本工具"],
      environmental: "环境影响最小，主要依靠人力作业",
    },
  ];

  // Flatten data for easy access
  if (project) {
    Object.entries(project).forEach(([key, value]) => {
      console.log(
        (data[`project_${key}`] = value),
        "(data[`project_${key}`] = value)"
      );

      return (data[`project_${key}`] = value);
    });
  }
  if (crossingPoint) {
    Object.entries(crossingPoint).forEach(
      ([key, value]) => (data[`crossing_${key}`] = value)
    );
  }
  if (scheme) {
    Object.entries(scheme).forEach(
      ([key, value]) => (data[`scheme_${key}`] = value)
    );

    data["schemeConstructionSteps"] = (scheme.constructionSteps || []).sort(
      (a, b) => (a.stepOrder || 0) - (b.stepOrder || 0)
    );
    data["schemeSchemeLevelSafetyMeasures"] =
      scheme.schemeLevelSafetyMeasures || [];
    data["schemeSchemeLevelQualityMeasures"] =
      scheme.schemeLevelQualityMeasures || [];
    data["schemeSchemeLevelEnvironmentalMeasures"] =
      scheme.schemeLevelEnvironmentalMeasures || [];
    data["schemeRequiredPersonnel"] = scheme.requiredPersonnel || [];
    data["schemeRequiredMaterials"] = scheme.requiredMaterials || [];
    data["schemeRequiredEquipment"] = scheme.requiredEquipment || [];
    data["schemeRequiredVehicles"] = scheme.requiredVehicles || [];
    data["crossingCrossingTypeLabel"] = getCrossingTypeLabel(
      crossingPoint?.crossingType
    );
    data["crossingDifficultyLevelLabel"] = getDifficultyLabel(
      crossingPoint?.difficultyLevel
    );
    data["schemeApprovalStatusLabel"] = getApprovalStatusLabel(
      scheme.approvalStatus
    );
  }

  // Add recommendations to data
  data["recommendations"] = recommendations;

  // System data
  data["systemCurrentDate"] = new Date().toLocaleDateString("zh-CN");
  data["systemGenerator"] = user?.fullName || "系统";
  data["systemGeneratedDatetime"] = new Date().toLocaleString("zh-CN");

  return data;
};

/**
 * 高级模板渲染引擎 - THE GOLDEN STANDARD
 * (Extracted from MarkdownTemplateEditor)
 */
function replaceTemplateVariables(template, data) {
  const maxDepth = 50;
  let depth = 0;

  function findMatchingEndTag(str, startIndex) {
    let openCount = 1;
    const openTag = "{{#each";
    const closeTag = "{{/each}}";
    let searchIndex = startIndex;
    while (openCount > 0) {
      const nextCloseIndex = str.indexOf(closeTag, searchIndex);
      const nextOpenIndex = str.indexOf(openTag, searchIndex);
      if (nextCloseIndex === -1) return -1;
      if (nextOpenIndex !== -1 && nextOpenIndex < nextCloseIndex) {
        openCount++;
        searchIndex = nextOpenIndex + openTag.length;
      } else {
        openCount--;
        if (openCount === 0) return nextCloseIndex;
        searchIndex = nextCloseIndex + closeTag.length;
      }
    }
    return -1;
  }

  function render(templateStr, context, parentThis = null) {
    if (depth >= maxDepth) return "[模板渲染已达到最大递归深度]";
    depth++;
    let output = "";
    let lastIndex = 0;
    const loopStartRegex = /\{\{#each\s+([\w_.]+)\}\}/g;
    let match;

    while ((match = loopStartRegex.exec(templateStr)) !== null) {
      output += templateStr.substring(lastIndex, match.index);
      const blockStartIndex = match.index + match[0].length;
      const blockEndIndex = findMatchingEndTag(templateStr, blockStartIndex);
      if (blockEndIndex === -1) {
        console.error("Unmatched {{#each}} block:", match[0]);
        lastIndex = match.index + match[0].length;
        loopStartRegex.lastIndex = lastIndex;
        continue;
      }
      const body = templateStr.substring(blockStartIndex, blockEndIndex);
      const arrayName = match[1];
      let array = [];
      try {
        if (arrayName === "this") array = parentThis;
        else if (arrayName.startsWith("this."))
          array = arrayName
            .substring(5)
            .split(".")
            .reduce((o, i) => o && o[i], parentThis);
        else array = arrayName.split(".").reduce((o, i) => o && o[i], context);
      } catch (e) {
        array = [];
      }
      if (Array.isArray(array)) {
        array.forEach((item, index) => {
          const itemContext = {
            ...context,
            index: index,
            indexPlus_1: index + 1,
          };
          if (typeof item === "object" && item !== null)
            Object.assign(itemContext, item);
          output += render(body, itemContext, item);
        });
      }
      lastIndex = blockEndIndex + "{{/each}}".length;
      loopStartRegex.lastIndex = lastIndex;
    }
    output += templateStr.substring(lastIndex);

    let processedOutput = output;
    const ifRegex =
      /\{\{#if\s+([\w_.]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g;
    processedOutput = processedOutput.replace(
      ifRegex,
      (match, conditionName, ifBody, elseBody = "") => {
        let value;
        try {
          if (conditionName === "this") value = parentThis;
          else if (conditionName.startsWith("this."))
            value = conditionName
              .substring(5)
              .split(".")
              .reduce((o, i) => o && o[i], parentThis);
          else
            value = conditionName
              .split(".")
              .reduce((o, i) => o && o[i], context);
        } catch (e) {
          value = undefined;
        }
        const isTruthy =
          value !== null &&
          value !== undefined &&
          value !== false &&
          value !== "false" &&
          !(Array.isArray(value) && value.length === 0) &&
          !(typeof value === "string" && value.trim() === "") &&
          !(typeof value === "number" && value === 0);
        return render(isTruthy ? ifBody : elseBody, context, parentThis);
      }
    );

    const varRegex = /\{\{([\w_.]+|this)\}\}/g;
    processedOutput = processedOutput.replace(varRegex, (match, varName) => {
      if (
        varName.startsWith("#") ||
        varName.startsWith("/") ||
        varName === "else"
      )
        return match;
      let value;
      try {
        if (varName === "this") value = parentThis;
        else if (varName.startsWith("this."))
          value = varName
            .substring(5)
            .split(".")
            .reduce((o, i) => o && o[i], parentThis);
        else value = varName.split(".").reduce((o, i) => o && o[i], context);
      } catch (e) {
        value = undefined;
      }
      if (value === null || value === undefined) return "";
      if (typeof value === "object") {
        if (Array.isArray(value))
          return value.length > 0 ? `[${value.length} items]` : "[]";
        return JSON.stringify(value, null, 2);
      }
      return String(value);
    });
    depth--;
    return processedOutput;
  }
  return render(template, data);
}

export const renderMarkdownTemplate = (template, data) => {
  return replaceTemplateVariables(template, data);
};

/**
 * 计算施工方案所需资源
 */
export const calculateSchemeResources = async (
  methodCode,
  crossingPoint,
  constructionSteps = []
) => {
  if (!methodCode || !crossingPoint) {
    return {
      materials: [],
      personnel: [],
      equipment: [],
      vehicles: [],
    };
  }

  const spanLength = crossingPoint.spanLength || 0;
  const crossingHeight = crossingPoint.crossingHeight || 0;
  const difficulty = crossingPoint.difficultyLevel || "medium";
  const crossingType = crossingPoint.crossingType || "other";

  // 基础资源配置
  const baseResources = {
    materials: [],
    personnel: [],
    equipment: [],
    vehicles: [],
  };

  // 根据施工方法配置资源
  switch (methodCode) {
    case "helicopterStringing":
      baseResources.materials = [
        {
          name: "迪尼玛导引绳",
          specification: "Φ6mm",
          unit: "m",
          quantity: Math.max(spanLength * 2, 1000),
        },
        {
          name: "钢丝绳",
          specification: "Φ8mm",
          unit: "m",
          quantity: spanLength + 500,
        },
        { name: "滑轮组", specification: "5T", unit: "套", quantity: 4 },
        { name: "绝缘材料", specification: "35kV", unit: "套", quantity: 2 },
      ];
      baseResources.personnel = [
        { role: "飞控师", quantity: 2, qualification: "持证飞行员" },
        { role: "架子工", quantity: 8, qualification: "高级工" },
        { role: "电工", quantity: 4, qualification: "特种作业证" },
        { role: "安全员", quantity: 2, qualification: "安全员证书" },
      ];
      baseResources.equipment = [
        { name: "对讲机", specification: "专业级", unit: "台", quantity: 10 },
        { name: "安全带", specification: "高空作业", unit: "套", quantity: 20 },
        { name: "安全帽", specification: "绝缘型", unit: "个", quantity: 20 },
        { name: "绝缘手套", specification: "35kV", unit: "双", quantity: 10 },
      ];
      baseResources.vehicles = [
        { type: "直升机", licensePlate: "待定", quantity: 1 },
        { type: "指挥车", licensePlate: "待定", quantity: 1 },
        { type: "工程车", licensePlate: "待定", quantity: 2 },
      ];
      break;

    case "groundStringing":
      baseResources.materials = [
        {
          name: "钢丝绳",
          specification: "Φ12mm",
          unit: "m",
          quantity: spanLength * 1.5,
        },
        { name: "滑轮组", specification: "10T", unit: "套", quantity: 6 },
        { name: "地锚", specification: "5T", unit: "个", quantity: 8 },
        { name: "绝缘材料", specification: "通用", unit: "套", quantity: 3 },
      ];
      baseResources.personnel = [
        { role: "项目经理", quantity: 1, qualification: "项目管理" },
        { role: "技术员", quantity: 2, qualification: "技术资格" },
        { role: "架子工", quantity: 10, qualification: "中级工" },
        { role: "普工", quantity: 8, qualification: "基础培训" },
        { role: "安全员", quantity: 2, qualification: "安全员证书" },
      ];
      baseResources.equipment = [
        { name: "张力机", specification: "20T", unit: "台", quantity: 1 },
        { name: "牵引机", specification: "15T", unit: "台", quantity: 1 },
        { name: "发电机", specification: "50kW", unit: "台", quantity: 2 },
        { name: "对讲机", specification: "普通型", unit: "台", quantity: 15 },
      ];
      baseResources.vehicles = [
        { type: "工程车", licensePlate: "待定", quantity: 3 },
        { type: "货车", licensePlate: "待定", quantity: 2 },
        { type: "指挥车", licensePlate: "待定", quantity: 1 },
      ];
      break;

    case "manualStringing":
      baseResources.materials = [
        {
          name: "钢丝绳",
          specification: "Φ6mm",
          unit: "m",
          quantity: spanLength + 200,
        },
        { name: "滑轮", specification: "普通型", unit: "个", quantity: 10 },
        { name: "安全绳", specification: "Φ12mm", unit: "m", quantity: 500 },
        { name: "基本工具", specification: "手动", unit: "套", quantity: 5 },
      ];
      baseResources.personnel = [
        { role: "技术员", quantity: 1, qualification: "技术资格" },
        { role: "架子工", quantity: 6, qualification: "中级工" },
        { role: "普工", quantity: 15, qualification: "基础培训" },
        { role: "安全员", quantity: 1, qualification: "安全员证书" },
      ];
      baseResources.equipment = [
        { name: "手摇绞车", specification: "2T", unit: "台", quantity: 4 },
        { name: "滑轮", specification: "手动", unit: "个", quantity: 20 },
        {
          name: "基本工具",
          specification: "手动工具",
          unit: "套",
          quantity: 10,
        },
      ];
      baseResources.vehicles = [
        { type: "皮卡", licensePlate: "待定", quantity: 2 },
        { type: "货车", licensePlate: "待定", quantity: 1 },
      ];
      break;

    case "scaffoldingErection":
      baseResources.materials = [
        {
          name: "钢管",
          specification: "Φ48×3.5",
          unit: "m",
          quantity: spanLength * 4 + 2000,
        },
        {
          name: "扣件",
          specification: "48mm",
          unit: "个",
          quantity: Math.floor(spanLength * 8) + 500,
        },
        {
          name: "安全网",
          specification: "阻燃型",
          unit: "m²",
          quantity: spanLength * 20,
        },
        {
          name: "脚手板",
          specification: "钢制",
          unit: "块",
          quantity: Math.floor(spanLength / 2) + 100,
        },
      ];
      baseResources.personnel = [
        { role: "项目经理", quantity: 1, qualification: "项目管理" },
        { role: "技术员", quantity: 2, qualification: "技术资格" },
        { role: "架子工", quantity: 15, qualification: "高级工" },
        { role: "普工", quantity: 10, qualification: "基础培训" },
        { role: "安全员", quantity: 2, qualification: "安全员证书" },
      ];
      baseResources.equipment = [
        {
          name: "脚手架",
          specification: "钢制",
          unit: "套",
          quantity: Math.floor(spanLength / 50) + 10,
        },
        { name: "吊车", specification: "25T", unit: "台", quantity: 2 },
        {
          name: "安全防护设备",
          specification: "全套",
          unit: "套",
          quantity: 30,
        },
      ];
      baseResources.vehicles = [
        { type: "吊车", licensePlate: "待定", quantity: 2 },
        { type: "平板运输车", licensePlate: "待定", quantity: 3 },
        { type: "工程车", licensePlate: "待定", quantity: 2 },
      ];
      break;

    default:
      // 默认配置
      baseResources.materials = [
        { name: "通用材料", specification: "标准", unit: "套", quantity: 1 },
      ];
      baseResources.personnel = [
        { role: "技术员", quantity: 1, qualification: "基础" },
        { role: "普工", quantity: 5, qualification: "基础培训" },
      ];
      baseResources.equipment = [
        { name: "基本工具", specification: "标准", unit: "套", quantity: 1 },
      ];
      baseResources.vehicles = [
        { type: "工程车", licensePlate: "待定", quantity: 1 },
      ];
  }

  // 根据难度调整资源数量
  const difficultyMultiplier =
    {
      low: 0.8,
      medium: 1.0,
      high: 1.3,
      critical: 1.6,
    }[difficulty] || 1.0;

  // 应用难度系数
  baseResources.materials.forEach((item) => {
    item.quantity = Math.ceil(item.quantity * difficultyMultiplier);
  });

  baseResources.personnel.forEach((item) => {
    item.quantity = Math.ceil(item.quantity * difficultyMultiplier);
  });

  baseResources.equipment.forEach((item) => {
    item.quantity = Math.ceil(item.quantity * difficultyMultiplier);
  });

  baseResources.vehicles.forEach((item) => {
    item.quantity = Math.ceil(item.quantity * difficultyMultiplier);
  });

  return baseResources;
};

/**
 * 智能推荐函数 - 为跨越点生成施工方案推荐
 */
export const getRecommendationsForCrossing = async (crossingPoint, project) => {
  if (!crossingPoint) return [];

  // 根据跨越点特征分析难度和风险
  const difficulty = crossingPoint.difficultyLevel || "medium";
  const spanLength = crossingPoint.spanLength || 0;
  const crossingHeight = crossingPoint.crossingHeight || 0;
  const crossingType = crossingPoint.crossingType || "other";

  // 成本估算基础函数
  const estimateCost = (baseCost, difficulty) => {
    let multiplier = 1.0;
    if (difficulty === "medium") multiplier = 1.2;
    else if (difficulty === "high") multiplier = 1.5;
    else if (difficulty === "critical") multiplier = 2.0;
    return Math.round(baseCost * multiplier * 10) / 10; // 保留一位小数
  };

  // 基础推荐方案列表
  const baseRecommendations = [
    {
      method: "helicopterStringing",
      name: "直升机架线法",
      score: 95,
      cost: estimateCost(15, difficulty),
      duration: 2, // 天数
      personnel: 8,
      risk:
        difficulty === "high" || difficulty === "critical" ? "medium" : "low",
      reasoning:
        "采用直升机进行架线作业，可快速完成跨越，减少对交通的影响，适合高难度跨越场景。",
      pros: [
        "施工速度快，工期短",
        "对交通影响最小",
        "技术成熟，安全可靠",
        "不需要大面积场地准备",
      ],
      cons: ["成本相对较高", "受天气影响较大", "需要专业直升机作业队伍"],
      equipment: ["直升机", "牵引设备", "通信设备", "安全防护用具"],
      environmental: "对环境影响最小，无需大规模场地清理",
    },
    {
      method: "groundStringing",
      name: "地面拖拉架线法",
      score: 80,
      cost: estimateCost(8, difficulty),
      duration: 3, // 天数
      personnel: 12,
      risk: difficulty === "critical" ? "high" : "medium",
      reasoning: "采用地面拖拉设备进行架线，成本适中，适用于多数跨越场景。",
      pros: ["成本相对较低", "设备投入适中", "技术要求不高", "作业相对灵活"],
      cons: ["需要较长封路时间", "对交通影响较大", "受地形条件限制"],
      equipment: ["拖拉机械", "滑轮组", "钢丝绳", "张力放线设备"],
      environmental: "需要临时道路和作业场地，对环境有一定影响",
    },
    {
      method: "manualStringing",
      name: "人工牵引架线法",
      score: 60,
      cost: estimateCost(5, difficulty),
      duration: 5, // 天数
      personnel: 20,
      risk:
        difficulty === "critical"
          ? "high"
          : difficulty === "high"
          ? "medium"
          : "low",
      reasoning:
        "采用人工方式进行架线，成本最低，但工期较长，适合简单跨越场景。",
      pros: ["成本最低", "设备需求最少", "对环境扰动小", "作业灵活性高"],
      cons: ["工期较长", "劳动强度大", "受人员技能影响", "不适合复杂跨越"],
      equipment: ["手摇绞车", "滑轮", "安全绳索", "基本工具"],
      environmental: "环境影响最小，主要依靠人力作业",
    },
  ];

  // 根据跨越点特征调整推荐分数
  const adjustedRecommendations = baseRecommendations.map((rec) => {
    let adjustedScore = rec.score;

    // 根据档距调整分数
    if (spanLength > 500) {
      if (rec.method === "helicopterStringing") adjustedScore += 5;
      if (rec.method === "manualStringing") adjustedScore -= 15;
    } else if (spanLength < 200) {
      if (rec.method === "manualStringing") adjustedScore += 10;
      if (rec.method === "helicopterStringing") adjustedScore -= 5;
    }

    // 根据跨越高度调整分数
    if (crossingHeight > 50) {
      if (rec.method === "helicopterStringing") adjustedScore += 10;
      if (rec.method === "manualStringing") adjustedScore -= 10;
    }

    // 根据跨越类型调整分数
    if (
      crossingType === "highwayExpressway" ||
      crossingType === "railwayHighSpeed"
    ) {
      if (rec.method === "helicopterStringing") adjustedScore += 15;
      if (rec.method === "groundStringing") adjustedScore -= 10;
    }

    // 确保分数在合理范围内
    adjustedScore = Math.max(30, Math.min(100, adjustedScore));

    return {
      ...rec,
      score: Math.round(adjustedScore),
    };
  });

  // 按分数降序排序
  return adjustedRecommendations.sort((a, b) => b.score - a.score);
};

/**
 * 生成Markdown格式的施工方案文档
 */
export const generateMarkdownForScheme = (scheme, crossingPoint, project) => {
  const data = prepareTemplateData(scheme, crossingPoint, project);

  // 基础Markdown模板
  const template = `# {{schemeName}}

## 1. 工程概况

**项目名称**: {{projectName}}
**跨越点名称**: {{crossingName}}
**跨越对象**: {{crossingCrossingObject}}
**跨越类型**: {{crossingCrossingTypeLabel}}
**施工方法**: {{schemeConstructionMethod}}

## 2. 技术参数

- **档距**: {{crossingSpanLength}}m
- **跨越高度**: {{crossingCrossingHeight}}m
- **对地距离**: {{crossingGroundClearance}}m
- **交叉角度**: {{crossingCrossingAngle}}°
- **设计风速**: {{crossingWindSpeed}}m/s

## 3. 施工步骤

{{#each schemeConstructionSteps}}
### 步骤{{stepOrder}}: {{stepName}}

**描述**: {{description}}
**工期**: {{durationDays}}天
**人员**: {{personnelCount}}人

{{#if technicalMeasures}}
**技术措施**:
{{#each technicalMeasures}}
- {{this}}
{{/each}}
{{/if}}

{{#if safetyMeasures}}
**安全措施**:
{{#each safetyMeasures}}
- {{this}}
{{/each}}
{{/if}}

{{/each}}

## 4. 资源需求

{{#if schemeRequiredMaterials}}
### 材料清单
{{#each schemeRequiredMaterials}}
- {{name}} {{specification}} × {{quantity}} {{unit}}
{{/each}}
{{/if}}

{{#if schemeRequiredEquipment}}
### 设备清单
{{#each schemeRequiredEquipment}}
- {{name}} {{specification}} × {{quantity}} {{unit}}
{{/each}}
{{/if}}

{{#if schemeRequiredPersonnel}}
### 人员配置
{{#each schemeRequiredPersonnel}}
- {{role}}: {{quantity}}人 ({{qualification}})
{{/each}}
{{/if}}

---
*文档生成时间: {{systemGeneratedDatetime}}*
*生成人: {{systemGenerator}}*`;

  return renderMarkdownTemplate(template, data);
};

// Main export object
const frontendLogic = {
  prepareTemplateData,
  renderMarkdownTemplate,
  getRecommendationsForCrossing,
  generateMarkdownForScheme,
  calculateSchemeResources, // Add the new function to the export
};

export { frontendLogic };
